import React, { useEffect, useState } from 'react';
import moment from 'moment';
import { features, useTablePipeline } from 'ali-react-table';
import { Button, Checkbox, Dropdown, Menu, message, Spin, Tabs, Tooltip } from 'antd';
import { splitArrayByIntersection } from '../../tool';
import { AntdBaseTable } from '@/base/TBaseTable';
import { PlusOutlined } from '#/utils/antdIcons.js';
import { TRDefault } from '@/components/index.js';
import { HttpCode } from '#/utils/contacts.js';
import { STATION_ID_MAP } from '../../help';
import {
  ConfirmModal,
  ConnectNSModal,
  CreateBatchTodoForNSModal,
  CreateBatchTodoModal,
  Detail,
  NoticeModal,
  SequenceModal,
  SetRemindersModal,
  TodoModal,
} from '../index';
import {
  ADD_MENU_LIST,
  DETAIL_TYPES,
  NOTICE_AND_SEQUENCE_OPTIONS,
  NOTICE_SEQUENCE_OPTIONS_LIST,
  TABS_LIST,
  TABS_LIST_TYPES,
  TODO_OPTIONS,
  TODO_OPTIONS_LIST,
  TODO_STATUS,
  TODO_STATUS_TYPES,
  TYPE_LIST,
  TYPE_LIST_ARR,
} from '../../dictionary';
import type {
  INoticeDetailType,
  INoticeSequenceListType,
  IOption,
  ISearchFormData,
  ISequenceDetailType,
  ITodoDetailType,
  ITodoListType,
} from '../../type';
import {
  batchRemovePendingH,
  editAttachmentCustomH,
  editNoticeCustomH,
  noticeSequenceDetailH,
  queryPendingDetailH,
} from '../../service';
import styles from './index.less';

interface IProps {
  /**
   * 列表数据源
   */
  dataSource: Record<string, any>[];
  /**
   * 设置表格数据loading
   */
  setComponentsLoadingStatus: (status: ICompontentsIsLoading) => void;
  /**
   * 搜索
   */
  setSearchCriteriaData: (params: any) => any;
  /**
   * 是否在加载中
   */
  isLoading: boolean;
  /**
   * 搜索所有数据
   */
  searchFormData: ISearchFormData;
  /**
   * 刷新key值
   */
  setFlashKey: (e: string | number) => void;
  /**
   * 刷新key值
   */
  setMonthflashKey: (e: string) => void;
  /**
   * 刷新基础数据
   */
  getSearchFormData: () => void;
  /**
   * 是否查询列表异常
   */
  isError?: boolean;
  /**
   * 按钮权限
   */
  buttonPermissions?: any;
  /**
   * 判断是否清空已选数据
   */
  selectFlashKey?: number;

  /**
   * 设置当前Tabs activeKey
   */
  setActiveKey: any;
  /**
   * 当前Tabs activeKey
   */
  activeKey: TABS_LIST;
  /**
   * 选择的当前月份
   */
  checkedDate: any;
}

const { TabPane } = Tabs;

const List = (props: IProps) => {
  const {
    dataSource = [],
    isLoading,
    searchFormData,
    isError = false,
    buttonPermissions = [],
    selectFlashKey,
    setMonthflashKey,
    setSearchCriteriaData,
    setComponentsLoadingStatus,
    setFlashKey,
    getSearchFormData,
    activeKey,
    setActiveKey,
    checkedDate,
  } = props;
  const [selectedRowKeys, setSelectedRowKeys] = useState<number[]>([]);
  const [detailVisible, setDetailVisible] = useState<boolean>(false);
  const [detailDataSource, setDetailDataSource] = useState<
    ITodoDetailType[] | INoticeDetailType[] | ISequenceDetailType[]
  >([]);
  const [detailKey, setDetailKey] = useState<DETAIL_TYPES>(DETAIL_TYPES.TODO);
  const [loading, setLoading] = useState<boolean>(false);
  const [detailIsError, setDetailIsError] = useState<boolean>(false);
  const [nowOption, setNowOption] = useState<IOption[]>(TODO_OPTIONS_LIST);
  const [recordData, setRecordData] = useState<any>({});
  const [detailMarketId, setDetailMarketId] = useState<string>('');
  useEffect(() => {
    setActiveKey(activeKey);
    if (activeKey === TABS_LIST.TODO_TABS_TYPE) {
      setNowOption(TODO_OPTIONS_LIST);
    } else {
      setNowOption(NOTICE_SEQUENCE_OPTIONS_LIST);
    }
    setSelectedRowKeys([]);
  }, [activeKey]);

  useEffect(() => {
    setDetailDataSource([]);
    setDetailVisible(false);
  }, [isLoading]);

  useEffect(() => {
    setSelectedRowKeys([]);
  }, [selectFlashKey]);

  // 切换Tabs
  const _onChange = (_activeKey?: string) => {
    setComponentsLoadingStatus({ listIsLoading: true });
    setLoading(true);
    setDetailDataSource([]);
    setActiveKey(_activeKey || TABS_LIST.TODO_TABS_TYPE);
    setDetailVisible(false);
    // 改1
    // setSearchCriteriaData({
    //   queryType: _activeKey || TABS_LIST.TODO_TABS_TYPE,
    // });
  };

  // 新增
  const onAdd = async (e: any) => {
    setDetailVisible(false);
    if (e.key === DETAIL_TYPES.TODO) {
      const hasSave =
        buttonPermissions?.filter((item: any) => item.menuCode === 'pendingSaveButtonV2')?.length >
        0;
      if (!hasSave) {
        return message.info('请联系管理员获取相关权限');
      }
      await TodoModal.show({
        searchFormData: searchFormData,
        isEdit: false,
        setFlashKey: setFlashKey,
        setMonthflashKey: setMonthflashKey,
        getSearchFormData,
        buttonPermissions,
      });
    } else if (e.key === DETAIL_TYPES.NOTICE) {
      const hasSave =
        buttonPermissions?.filter((item: any) => item.menuCode === 'noticeSaveButtonV2')?.length >
        0;
      if (!hasSave) {
        return message.info('请联系管理员获取相关权限');
      }
      await NoticeModal.show({
        searchFormData: searchFormData,
        isEdit: false,
        setFlashKey: setFlashKey,
        setMonthflashKey: setMonthflashKey,
      });
    } else if (e.key === DETAIL_TYPES.SEQUENCE) {
      const hasSave =
        buttonPermissions?.filter((item: any) => item.menuCode === 'attachSaveButtonV2')?.length >
        0;
      if (!hasSave) {
        return message.info('请联系管理员获取相关权限');
      }
      await SequenceModal.show({
        searchFormData: searchFormData,
        isEdit: false,
        setFlashKey: setFlashKey,
        setMonthflashKey: setMonthflashKey,
      });
    }
  };

  // 删除待办
  const onDeleteTodo = async (params: { id: number[]; hintText: string; title: string }) => {
    const { id, title = '', hintText = '' }: any = params;
    const ids: any = [];

    dataSource.forEach((item) => {
      ids.push(item.id);
    });
    await ConfirmModal.show({
      title,
      hintText,
      onOk: async () => {
        let res: any;
        if (splitArrayByIntersection(id, ids).intersection.length > 0) {
          res = await batchRemovePendingH({
            id: splitArrayByIntersection(id, ids).intersection,
          });
        }

        if (res && res.statusCode === HttpCode.SUCCESS) {
          message.info('删除成功！');
          setFlashKey(String(moment().valueOf()));
          setMonthflashKey(String(moment().valueOf()));
        } else {
          message.info(res?.message || '删除失败！');
        }
      },
    });
  };

  // 删除公告或者序列
  const onDeleteNoticeAndSequence = async (params: {
    data: any;
    type: number;
    activeKey?: TABS_LIST;
  }) => {
    const ids: any = [];

    dataSource.forEach((item) => {
      ids.push(item.id);
    });

    const { data, type } = params;
    let res: any;
    if (type === 1) {
      await ConfirmModal.show({
        title: activeKey === TABS_LIST.NOTICE_TABS_TYPE ? '删除公告' : '删除序列',
        hintText:
          activeKey === TABS_LIST.NOTICE_TABS_TYPE
            ? '是否确认删除本公告？'
            : '是否确认删除本序列？',
        onOk: async () => {
          if ((data as INoticeSequenceListType).type === TYPE_LIST.CUSTOM_NOTICE) {
            res = await editNoticeCustomH({
              delete: [{ noticeId: (data as INoticeSequenceListType).id }],
            });
          } else if ((data as INoticeSequenceListType).type === TYPE_LIST.CUSTOM_SEQUENCE) {
            res = await editAttachmentCustomH({
              delete: [{ tradeSequenceId: (data as INoticeSequenceListType).id }],
            });
          }
        },
      });
    } else {
      let hintText: string = '';
      const {
        customNoticeArr = [],
        customSequenceArr = [],
        systemNoticeArr = [],
        systemSequenceArr = [],
      } = data || {};
      if (systemNoticeArr?.length > 0 || systemSequenceArr.length > 0) {
        hintText =
          activeKey === TABS_LIST.NOTICE_TABS_TYPE
            ? `所选公告中包含系统创建的有${systemNoticeArr?.length}条不可删除，是否确认删除其余公告？`
            : `所选序列中包含系统创建的有${systemSequenceArr?.length}条不可删除，是否确认删除其余序列？`;
      } else {
        hintText =
          activeKey === TABS_LIST.NOTICE_TABS_TYPE
            ? '是否确认删除所选公告？'
            : '是否确认删除所选序列？';
      }
      await ConfirmModal.show({
        title: activeKey === TABS_LIST.NOTICE_TABS_TYPE ? '批量删除公告' : '批量删除序列',
        hintText,
        onOk: async () => {
          if (customNoticeArr.length > 0) {
            res = await editNoticeCustomH({
              delete: splitArrayByIntersection(customNoticeArr, ids).intersection,
            });
          }
          if (customSequenceArr.length > 0) {
            res = await editAttachmentCustomH({
              delete: splitArrayByIntersection(customSequenceArr, ids).intersection,
            });
          }
        },
      });
    }
    if (res && res.statusCode === HttpCode.SUCCESS) {
      message.info('删除成功！');
      setFlashKey(String(moment().valueOf()));
      setMonthflashKey(String(moment().valueOf()));
      setSelectedRowKeys([]);
    } else if (res) {
      message.info(res?.message || '删除失败！');
    }
  };

  // 控制详情展示与关闭
  const handelVisible = (e: boolean) => {
    setDetailVisible(e);
  };

  // 查询待办/公告/序列详情
  const showDetail = async (record: any, type: DETAIL_TYPES) => {
    setLoading(true);
    handelVisible(true);
    setDetailMarketId(record.marketId);
    setRecordData(record);
    setDetailKey(type);
    if (activeKey === TABS_LIST.TODO_TABS_TYPE) {
      if (type === DETAIL_TYPES.TODO) {
        const param = { id: [record.id] };
        let res: any = {};
        res = await queryPendingDetailH(param);

        if (res && res.statusCode === HttpCode.SUCCESS) {
          setDetailDataSource(res.data);
          setDetailIsError(false);
        } else {
          setDetailDataSource([]);
          setDetailIsError(true);
          message.info(res?.message || '系统异常');
        }
      } else if (type === DETAIL_TYPES.NOTICE) {
        const param = {
          idList: record?.relaNotice ? record?.relaNotice.split(',') : [],
          type: TABS_LIST.NOTICE_TABS_TYPE,
        };
        let res: any = {};
        res = await noticeSequenceDetailH(param);
        if (res && res.statusCode === HttpCode.SUCCESS) {
          setDetailDataSource(res.data);
          setDetailIsError(false);
        } else {
          setDetailDataSource([]);
          setDetailIsError(true);
          message.info(res?.message || '系统异常');
        }
      } else {
        const param = {
          idList: record?.relaSequence ? record?.relaSequence.split(',') : [],
          type: TABS_LIST.SEQUENCE_TABS_TYPE,
        };
        let res: any = {};
        res = await noticeSequenceDetailH(param);
        if (res && res.statusCode === HttpCode.SUCCESS) {
          setDetailDataSource(res.data);
          setDetailIsError(false);
        } else {
          setDetailDataSource([]);
          setDetailIsError(true);
          message.info(res?.message || '系统异常');
        }
      }
    } else {
      if (type === DETAIL_TYPES.TODO) {
        const param = {
          id: record?.relatedPendingIds ? record?.relatedPendingIds?.split(',') : [],
        };
        let res: any = {};
        res = await queryPendingDetailH(param);
        if (res && res.statusCode === HttpCode.SUCCESS) {
          setDetailDataSource(res.data);
          setDetailIsError(false);
        } else {
          setDetailDataSource([]);
          setDetailIsError(true);
          message.info(res?.message || '系统异常');
        }
      } else if (type === DETAIL_TYPES.NOTICE) {
        const param = { idList: [record?.id], type: TABS_LIST.NOTICE_TABS_TYPE };
        let res: any = {};
        res = await noticeSequenceDetailH(param);
        if (res && res.statusCode === HttpCode.SUCCESS) {
          setDetailDataSource(res.data);
          setDetailIsError(false);
        } else {
          setDetailDataSource([]);
          setDetailIsError(true);
          message.info(res?.message || '系统异常');
        }
      } else {
        const param = { idList: [record?.id], type: TABS_LIST.SEQUENCE_TABS_TYPE };
        let res: any = {};
        res = await noticeSequenceDetailH(param);
        if (res && res.statusCode === HttpCode.SUCCESS) {
          setDetailDataSource(res.data);
          setDetailIsError(false);
        } else {
          message.info(res?.message || '系统异常');
          setDetailIsError(true);
          setDetailDataSource([]);
        }
      }
    }
    setLoading(false);
  };

  // 批量操作
  const onBatch = async (e: any) => {
    if (activeKey === TABS_LIST.TODO_TABS_TYPE) {
      if (e.key === '1') {
        const hasSave =
          buttonPermissions?.filter((item: any) => item.menuCode === 'pendingBatchSaveButtonV2')
            ?.length > 0;
        if (!hasSave) {
          return message.info('请联系管理员获取相关权限');
        }
      } else if (e.key === '2') {
        const hasSave =
          buttonPermissions?.filter((item: any) => item.menuCode === 'batchReminderButtonV2')
            ?.length > 0;
        if (!hasSave) {
          return message.info('请联系管理员获取相关权限');
        }
      } else if (e.key === '3') {
        const hasSave =
          buttonPermissions?.filter((item: any) => item.menuCode === 'pendingBatchRemoveButtonV2')
            ?.length > 0;
        if (!hasSave) {
          return message.info('请联系管理员获取相关权限');
        }
      }
    } else if (
      activeKey === TABS_LIST.NOTICE_TABS_TYPE ||
      activeKey === TABS_LIST.SEQUENCE_TABS_TYPE
    ) {
      if (e.key === '1') {
        const hasSave =
          buttonPermissions?.filter(
            (item: any) => item.menuCode === 'noticeAttachBatchAddPendingV2',
          )?.length > 0;
        if (!hasSave) {
          return message.info('请联系管理员获取相关权限');
        }
      } else if (e.key === '2') {
        const hasSave =
          buttonPermissions?.filter(
            (item: any) => item.menuCode === 'noticeAttachBatchRemoveButtonV2',
          )?.length > 0;
        if (!hasSave) {
          return message.info('请联系管理员获取相关权限');
        }
      }
    }
    setDetailVisible(false);
    const warnText =
      activeKey === TABS_LIST.TODO_TABS_TYPE
        ? '请选择“待办”后操作'
        : activeKey === TABS_LIST.NOTICE_TABS_TYPE
        ? '请选择“公告”后操作'
        : '请选择“序列”后操作';
    if (activeKey === TABS_LIST.TODO_TABS_TYPE && e.key === '1') {
      await CreateBatchTodoModal.show({
        searchFormData: searchFormData,
        setFlashKey: setFlashKey,
        setMonthflashKey: setMonthflashKey,
      });
    } else if (selectedRowKeys && selectedRowKeys.length > 0) {
      if (activeKey === TABS_LIST.TODO_TABS_TYPE) {
        if (e.key === '2') {
          await SetRemindersModal.show({
            searchFormData,
            isEdit: true,
            checkedDate,
            activeKey,
            value: {
              id: selectedRowKeys,
            },
            getSearchFormData,
          });
        } else if (e.key === '3') {
          // 批量删除待办
          onDeleteTodo({
            id: selectedRowKeys,
            title: '批量删除待办',
            hintText: '是否删除所选待办？',
          });
        }
      } else if (
        activeKey === TABS_LIST.NOTICE_TABS_TYPE ||
        activeKey === TABS_LIST.SEQUENCE_TABS_TYPE
      ) {
        if (e.key === '1') {
          const data = selectedRowKeys.map((i) => {
            let obj = dataSource.find((item) => item.id === i);
            if (obj) {
              obj = {
                calendarDate: obj?.date,
                transactionArrange: obj.content,
                stationList: obj?.stationIds ? obj?.stationIds?.split(',') : [],
                relaType: obj?.type,
                isHlj: splitArrayByIntersection(obj?.stationIds?.split(','), STATION_ID_MAP.PDBLJ)
                  .hasIntersection,
                relaId: obj?.id,
                declarationEndTime: obj?.declarationEndTime,
                declarationStartTime: obj?.declarationStartTime,
              };
              return obj;
            }
          });
          await CreateBatchTodoForNSModal.show({
            searchFormData: searchFormData,
            value: data,
            setFlashKey: setFlashKey,
            setMonthflashKey: setMonthflashKey,
          });
        } else if (e.key === '2') {
          const systemNoticeArr: any = []; //系统公告
          const customNoticeArr: any = []; //自定义公告
          const systemSequenceArr: any = []; //自定义序列
          const customSequenceArr: any = []; //系统序列
          selectedRowKeys.forEach((item) => {
            const obj: any = dataSource.find((i) => i.id === item);
            if (obj?.type === TYPE_LIST.CUSTOM_NOTICE) {
              customNoticeArr.push({ noticeId: obj?.id });
            } else if (obj?.type === TYPE_LIST.SYSTEM_NOTICE) {
              systemNoticeArr.push({ noticeId: obj?.id });
            } else if (obj?.type === TYPE_LIST.CUSTOM_SEQUENCE) {
              customSequenceArr.push({ tradeSequenceId: obj?.id });
            } else {
              systemSequenceArr.push({ tradeSequenceId: obj?.id });
            }
          });
          onDeleteNoticeAndSequence({
            data: {
              customNoticeArr,
              systemNoticeArr,
              systemSequenceArr,
              customSequenceArr,
            },
            type: 2, // 1--> 单独删除，2--> 批量删除
            activeKey: activeKey,
          });
        }
      }
    } else {
      message.info(warnText || '请选择');
    }
  };

  // 关联公告或者序列
  const conncetNoticeOrSequence = async (record: any) => {
    const noticeArr = record?.relaNotice ? record?.relaNotice.split(',') : [];
    const sequenceArr = record?.relaSequence ? record?.relaSequence.split(',') : [];
    let data: any = [];
    let list: any = [];
    if (noticeArr?.length > 0) {
      const param = {
        idList: record?.relaNotice ? record?.relaNotice.split(',') : [],
        type: TABS_LIST.NOTICE_TABS_TYPE,
      };
      let res: any = {};
      res = await noticeSequenceDetailH(param);

      if (res && res.statusCode === HttpCode.SUCCESS) {
        const arr = res.data.map((item: INoticeDetailType) => {
          return {
            id: item.id,
            date: item.publishTime, //日期
            marketName: item.marketName, //交易中心
            type: item.type, //类型（公告、交易序列）
            content: item.title, //内容
            declarationStartTime: null, //交易时间起
            declarationEndTime: null, //交易时间止
            executionStartDate: null, //执行时间起
            executionEndDate: null, //执行时间止
            createUserName: item.createUserName, //创建人
          };
        });
        data = [...data, ...arr];
        list = [...list, ...noticeArr];
      }
    }
    if (sequenceArr?.length > 0) {
      const param = {
        idList: record?.relaSequence ? record?.relaSequence.split(',') : [],
        type: TABS_LIST.SEQUENCE_TABS_TYPE,
      };
      let res: any = {};
      res = await noticeSequenceDetailH(param);
      if (res && res.statusCode === HttpCode.SUCCESS) {
        const arr = res.data.map((item: ISequenceDetailType) => {
          return {
            id: item.id,
            date: item.declarationStartTime, //日期
            marketName: item.marketName, //交易中心
            type: item.type, //类型（公告、交易序列）
            content: item.title, //内容
            declarationStartTime: item.declarationStartTime, //交易时间起
            declarationEndTime: item.declarationEndTime, //交易时间止
            executionStartDate: item.executionStartDate, //执行时间起
            executionEndDate: item.executionEndDate, //执行时间止
            createUserName: item.createUserName, //创建人
          };
        });
        data = [...data, ...arr];
        list = [...list, ...sequenceArr];
      }
    }
    await ConnectNSModal.show({
      id: record.id,
      searchFormData: searchFormData,
      setFlashKey: setFlashKey,
      value: list,
      data: data,
      marketId: record.marketId,
    });
  };

  // 提醒设置
  const handleSetWarn = async (record: ITodoListType) => {
    const hasSave =
      buttonPermissions?.filter((item: any) => item.menuCode === 'reminderButtonV2')?.length > 0;
    if (!hasSave) {
      return message.info('请联系管理员获取相关权限');
    }
    const param = { id: [record.id] };
    const res = await queryPendingDetailH(param);
    if (res && res.statusCode === HttpCode.SUCCESS) {
      await SetRemindersModal.show({
        searchFormData,
        isEdit: true,
        checkedDate,
        activeKey,
        value: {
          ...res.data[0],
          id: res?.data[0]?.id ? [res?.data[0]?.id] : null,
        },
        getSearchFormData,
        marketId: record.marketId,
      });
    }
  };

  // 创建待办
  const createTodo = async (record: INoticeSequenceListType) => {
    const stationIds = record?.stationIds ? record?.stationIds?.split(',') : [];
    const stationNames = record?.stationNames ? record?.stationNames?.split(',') : [];
    const stationList = stationIds.map((item, i) => {
      return { value: item, label: stationNames[i] };
    });
    const result: any = await TodoModal.show({
      searchFormData: searchFormData,
      value: {
        ...record,
        transactionArrange: record?.content || '',
        stationList: stationList,
        pendingEndTime: record?.declarationEndTime,
        pendingStartTime: record?.declarationStartTime,
        calendarDate: record?.date || '',
        relaType: record?.type,
        relaId: record?.id,
      },
      isEdit: false,
      setFlashKey: setFlashKey,
      setMonthflashKey: setMonthflashKey,
      getSearchFormData,
      buttonPermissions,
      marketId: splitArrayByIntersection(record?.stationIds?.split(','), STATION_ID_MAP.PDBLJ)
        .hasIntersection
        ? 'PDBLJ'
        : '',
    });
    if (result && result.statusCode === HttpCode.SUCCESS) {
    }
  };

  // 执行操作
  const handleOption = (item: { label: string; value: number }, record: any) => {
    setDetailVisible(false);
    if (activeKey === TABS_LIST.TODO_TABS_TYPE) {
      switch (item.value) {
        case 1:
          conncetNoticeOrSequence(record);
          break;
        case 2:
          handleSetWarn(record);
          break;
        case 3:
          const hasSave =
            buttonPermissions?.filter((a: any) => a.menuCode === 'pendingRemoveButtonV2')?.length >
            0;
          if (!hasSave) {
            return message.info('请联系管理员获取相关权限');
          } else {
            onDeleteTodo({
              id: [record?.id],
              title: '删除待办',
              hintText: '是否确认删除本待办？',
            });
          }
          break;
        default:
          break;
      }
    } else if (
      activeKey === TABS_LIST.SEQUENCE_TABS_TYPE ||
      activeKey === TABS_LIST.NOTICE_TABS_TYPE
    ) {
      switch (item.value) {
        case 1:
          const hasSave1 =
            buttonPermissions?.filter((a: any) => a.menuCode === 'noticeAttachAddPendingV2')
              ?.length > 0;
          if (!hasSave1) {
            return message.info('请联系管理员获取相关权限');
          } else {
            createTodo(record as INoticeSequenceListType);
          }
          break;
        case 2:
          const hasSave =
            buttonPermissions?.filter(
              (item1: any) => item1.menuCode === 'noticeAttachRemoveButtonV2',
            )?.length > 0;
          if (!hasSave) {
            return message.info('请联系管理员获取相关权限');
          } else {
            onDeleteNoticeAndSequence({
              data: record,
              type: 1, // 1--> 单独删除，2--> 批量删除
            });
          }
          break;
        default:
          break;
      }
    }
  };

  const toDoColumns = [
    {
      code: 'calendarDate',
      name: '日期',
      width: 80,
      render(v: string) {
        return v ? moment(v).format('YYYYMMDD') : '-';
      },
    },
    {
      code: 'pendingStartTime',
      name: '待办时间',
      width: 80,
      render(v: string, record: ITodoListType) {
        const data =
          record.pendingStartTime && record.pendingEndTime
            ? `${moment(record.pendingStartTime).format('HHmm')}-${moment(
                record.pendingEndTime,
              ).format('HHmm')}`
            : '-';
        return data;
      },
    },
    {
      code: 'transactionArrange',
      name: '待办内容',
      width: 260,
      render(v: string, record: ITodoListType) {
        return (
          <Tooltip placement="topLeft" title={v} overlayClassName={styles.tooltip}>
            <div className={styles.online} onClick={() => showDetail(record, DETAIL_TYPES.TODO)}>
              {v}
            </div>
          </Tooltip>
        );
      },
    },
    {
      code: 'status',
      name: '状态',
      width: 80,
      render(v: number) {
        const data = TODO_STATUS_TYPES.find((item) => item.value === v);
        return (
          <div
            className={styles.tag}
            style={{ color: data?.color, backgroundColor: data?.backgroundColor }}
          >
            {data?.label}
          </div>
        );
      },
    },
    {
      code: 'createName',
      name: '创建人',
      width: 80,
      render(v: string) {
        return v || '-';
      },
    },
    {
      code: 'relaNotice',
      name: '关联公告',
      width: 80,
      render(v: string, record: ITodoListType) {
        const arr = v ? v.split(',') : [];
        return (
          <div
            style={{
              color: arr && arr.length ? '#18A0FB' : '#D3D4D4',
              cursor: arr && arr.length ? 'pointer' : '',
            }}
            onClick={() => {
              arr && arr.length && showDetail(record, DETAIL_TYPES.NOTICE);
            }}
          >
            {arr ? arr?.length : 0}
          </div>
        );
      },
    },
    {
      code: 'relaSequence',
      name: '关联序列',
      width: 80,
      render(v: string, record: ITodoListType) {
        const arr = v ? v.split(',') : [];

        return (
          <div
            style={{
              color: arr && arr.length ? 'var(--bd-primary)' : '',
              cursor: arr && arr.length ? 'pointer' : '',
            }}
            onClick={() => {
              arr && arr.length && showDetail(record, DETAIL_TYPES.SEQUENCE);
            }}
          >
            {arr ? arr?.length : 0}
          </div>
        );
      },
    },
    {
      code: 'options',
      name: '操作',
      width: 160,
      render(v: number, record: ITodoListType) {
        return (
          <div className={styles.options}>
            {TODO_OPTIONS.map((item) => {
              return (
                <div
                  className={styles.item}
                  key={item.value}
                  onClick={() => handleOption(item, record)}
                >
                  {item.label}
                </div>
              );
            })}
          </div>
        );
      },
    },
  ];

  const sequenceColumns = [
    {
      code: 'date',
      name: '日期',
      width: 80,
      render(v: string) {
        return v ? moment(v).format('YYYYMMDD') : '-';
      },
    },
    {
      code: 'marketName',
      name: '交易中心',
      width: 160,
      render(v: string) {
        return v || '-';
      },
    },
    {
      code: 'type',
      name: '类型',
      width: 80,
      render(v: string) {
        const data = TYPE_LIST_ARR.find((item) => item.value === v);
        return data?.label;
      },
    },
    {
      code: 'content',
      name: '内容',
      width: 280,
      render(v: string, record: INoticeSequenceListType) {
        return (
          <Tooltip placement="topLeft" title={v} overlayClassName={styles.tooltip}>
            <div
              className={styles.online}
              onClick={() => {
                const data = TYPE_LIST_ARR.find((item) => item.value === record.type);
                showDetail(record, data?.key || DETAIL_TYPES.NOTICE);
              }}
            >
              {v}
            </div>
          </Tooltip>
        );
      },
    },
    {
      code: 'declarationStartTime',
      name: '交易时间',
      width: 80,
      render(v: string, record: INoticeSequenceListType) {
        const data =
          record.declarationStartTime && record.declarationEndTime
            ? `${moment(record.declarationStartTime).format('HHmm')}-${moment(
                record.declarationEndTime,
              ).format('HHmm')}`
            : '-';
        return data;
      },
    },
    {
      code: 'executionStartDate',
      name: '执行起止时间',
      width: 160,
      render(v: string, record: INoticeSequenceListType) {
        const data =
          record.executionStartDate && record.executionEndDate
            ? `${moment(record.executionStartDate).format('YYYYMMDD')}-${moment(
                record.executionEndDate,
              ).format('YYYYMMDD')}`
            : '-';
        return data;
      },
    },
    {
      code: 'createUserName',
      name: '创建人',
      width: 80,
      render(v: string) {
        return v || '-';
      },
    },
    {
      code: 'relatedPendingIds',
      name: '关联待办',
      width: 80,
      render(v: string, record: INoticeSequenceListType) {
        const arr = v ? v.split(',') : [];
        return (
          <div
            style={{
              color: arr && arr.length ? 'var(--bd-primary)' : '',
              cursor: arr && arr.length ? 'pointer' : '',
            }}
            onClick={() => {
              arr && arr.length && showDetail(record, DETAIL_TYPES.TODO);
            }}
          >
            {arr ? arr?.length : 0}
          </div>
        );
      },
    },
    {
      code: 'options',
      name: '操作',
      width: 120,
      lock: true,
      render(v: number, record: INoticeSequenceListType) {
        return (
          <div className={styles.options}>
            {NOTICE_AND_SEQUENCE_OPTIONS.map((item) => {
              return (
                <div
                  className={`${
                    item.value === 2 &&
                    (record.type === TYPE_LIST.SYSTEM_NOTICE ||
                      record.type === TYPE_LIST.SYSTEM_SEQUENCE)
                      ? styles.disableItem
                      : styles.item
                  }`}
                  key={item.value}
                  onClick={() => {
                    !(
                      item.value === 2 &&
                      (record.type === TYPE_LIST.SYSTEM_NOTICE ||
                        record.type === TYPE_LIST.SYSTEM_SEQUENCE)
                    ) && handleOption(item, record);
                  }}
                >
                  {item.label}
                </div>
              );
            })}
          </div>
        );
      },
    },
    {},
  ];

  const noticeColumns = [
    {
      code: 'date',
      name: '日期',
      width: 80,
      render(v: string) {
        return v ? moment(v).format('YYYYMMDD') : '-';
      },
    },
    {
      code: 'marketName',
      name: '交易中心',
      width: 160,
      render(v: string) {
        return v || '-';
      },
    },
    {
      code: 'type',
      name: '类型',
      width: 80,
      render(v: string) {
        const data = TYPE_LIST_ARR.find((item) => item.value === v);
        return data?.label;
      },
    },
    {
      code: 'content',
      name: '内容',
      width: 280,
      render(v: string, record: INoticeSequenceListType) {
        return (
          <Tooltip placement="topLeft" title={v} overlayClassName={styles.tooltip}>
            <div
              className={styles.online}
              onClick={() => {
                const data = TYPE_LIST_ARR.find((item) => item.value === record.type);
                showDetail(record, data?.key || DETAIL_TYPES.NOTICE);
              }}
            >
              {v}
            </div>
          </Tooltip>
        );
      },
    },
    {
      code: 'categoryModuleName',
      name: '平台模块',
      width: 120,
      render(v: string) {
        return (
          <Tooltip placement="topLeft" title={v} overlayClassName={styles.tooltip}>
            <div>{v || '-'}</div>
          </Tooltip>
        );
      },
    },
    {
      code: 'createUserName',
      name: '创建人',
      width: 80,
      render(v: string) {
        return v || '-';
      },
    },
    {
      code: 'relatedPendingIds',
      name: '关联待办',
      width: 80,
      render(v: string, record: INoticeSequenceListType) {
        const arr = v ? v.split(',') : [];
        return (
          <div
            style={{
              color: arr && arr.length ? 'var(--bd-primary)' : '',
              cursor: arr && arr.length ? 'pointer' : '',
            }}
            onClick={() => {
              arr && arr.length && showDetail(record, DETAIL_TYPES.TODO);
            }}
          >
            {arr ? arr?.length : 0}
          </div>
        );
      },
    },
    {
      code: 'options',
      name: '操作',
      width: 120,
      lock: true,
      render(v: number, record: INoticeSequenceListType) {
        return (
          <div className={styles.options}>
            {NOTICE_AND_SEQUENCE_OPTIONS.map((item) => {
              return (
                <div
                  className={`${
                    item.value === 2 &&
                    (record.type === TYPE_LIST.SYSTEM_NOTICE ||
                      record.type === TYPE_LIST.SYSTEM_SEQUENCE)
                      ? styles.disableItem
                      : styles.item
                  }`}
                  key={item.value}
                  onClick={() => {
                    !(
                      item.value === 2 &&
                      (record.type === TYPE_LIST.SYSTEM_NOTICE ||
                        record.type === TYPE_LIST.SYSTEM_SEQUENCE)
                    ) && handleOption(item, record);
                  }}
                >
                  {item.label}
                </div>
              );
            })}
          </div>
        );
      },
    },
    {},
  ];

  // 新增列表
  const menu = (
    <Menu onClick={onAdd}>
      {ADD_MENU_LIST.map((item) => {
        return <Menu.Item key={item.value}>{item.label}</Menu.Item>;
      })}
    </Menu>
  );

  // 批量操作列表
  const batchOperations = (
    <Menu onClick={onBatch}>
      {nowOption.map((item) => {
        return <Menu.Item key={item.value}>{item.label}</Menu.Item>;
      })}
    </Menu>
  );

  const operations = () => {
    return (
      <Dropdown overlay={menu} placement="bottomCenter" overlayClassName={styles.dropdownA}>
        <Button type="link" icon={<PlusOutlined />}>
          新建
        </Button>
      </Dropdown>
    );
  };
  const pipeline = useTablePipeline({ components: { Checkbox } })
    .input({
      dataSource,
      // @ts-ignore
      columns:
        activeKey === TABS_LIST.TODO_TABS_TYPE
          ? toDoColumns
          : activeKey === TABS_LIST.NOTICE_TABS_TYPE
          ? noticeColumns
          : sequenceColumns,
    })
    .primaryKey('id') // 每一行数据由 id 字段唯一标记
    .use(
      features.multiSelect({
        // @ts-ignore
        value: selectedRowKeys,
        highlightRowWhenSelected: true,
        checkboxPlacement: 'start',
        checkboxColumn: { lock: true },
        clickArea: 'cell',
        onChange: (a, e) => {
          // @ts-ignore
          setSelectedRowKeys(a);
        },
      }),
    )
    .appendRowPropsGetter((_row): any => {
      const color = _row.status === TODO_STATUS.OVERDUE_TYPE ? '#383C3E' : '#222629';
      return {
        style: { '--bgcolor': color, '--hover-bgcolor': color },
      };
    });

  // 渲染table组件
  const renderTable = () => {
    return isError ? (
      <TRDefault type={'error'} message={'系统异常'} />
    ) : (
      <Spin spinning={isLoading}>
        {isLoading ? null : !dataSource.length ? (
          <TRDefault type={'emptysm'} message={'暂无数据'} />
        ) : (
          <div className={styles.table}>
            <div className={styles.option}>
              <Dropdown
                overlay={batchOperations}
                placement="bottomCenter"
                overlayClassName={styles.dropdownA}
              >
                <Button>批量操作</Button>
              </Dropdown>
            </div>
            <div className={styles.antdBaseTable}>
              <AntdBaseTable
                useVirtual={true}
                style={{
                  '--row-height': '28px',
                  // '--header-bgcolor': '#383C3E',
                  '--header-row-height': '28px',
                  '--cell-padding': '4px',
                  // '--cell-border-vertical': '1px solid #4E5154',
                  // '--header-cell-border-vertical': '1px solid #4E5154',
                  // '--highlight-bgcolor': '#21323E',
                  borderRadius: '5px',
                  // border: '1px solid #4E5154',
                  width: '100%',
                  height: '100%',
                  overflow: 'auto',
                }}
                {...pipeline.getProps()}
              />
            </div>
          </div>
        )}
      </Spin>
    );
  };

  return (
    <div className={styles.container}>
      <div
        className={`${styles.rightTopContent} ${detailVisible ? styles.topScale : styles.rightTop}`}
      >
        <Tabs tabBarExtraContent={operations()} activeKey={activeKey} onChange={_onChange}>
          {TABS_LIST_TYPES.map((item: { title: string; key: TABS_LIST }) => {
            return (
              <TabPane tab={item.title} key={item.key}>
                {renderTable()}
              </TabPane>
            );
          })}
        </Tabs>
      </div>
      {detailVisible ? (
        <div className={styles.rightBottom}>
          <Detail
            visible={detailVisible}
            buttonPermissions={buttonPermissions}
            handelVisible={handelVisible}
            dataSource={detailDataSource}
            detailKey={detailKey}
            loading={loading}
            marketId={detailMarketId}
            isError={detailIsError}
            activeKey={activeKey}
            searchFormData={searchFormData}
            setFlashKey={setFlashKey}
            setMonthflashKey={setMonthflashKey}
            showDetail={showDetail}
            recordData={recordData}
            getSearchFormData={getSearchFormData}
          />
        </div>
      ) : null}
    </div>
  );
};

export default List;
